import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Row, Col, Slider, InputNumber, Button, Spin,Divider } from 'antd';
import styled from 'styled-components';
import _ from 'lodash';
import SVG from 'svg.js';

const Canvas = styled.div`
	width: 100%;
	height: 100%;
	overflow: hidden;
	margin-bottom: 1em;
`;

const FlexCol = styled.div`
	display: flex;
	height: 100%;
	width: 100%;
	flex-direction: column;
	justify-content: space-between;
`;

export default class ImageEraser extends Component {
	constructor(props) {
		super(props);
		this.onDraw = false;
		this.canvas = this.cursor = undefined;
		this.tmpCircle = []; // 临时的路径
		this.polyLines = []; // 路径集合
		this.state = {
			loading: 0, // 加载图片状态
			submitLoading: 0, // 合成base64状态
			radius: 30,
			visible: false,
			revertStatus: false
		};
		// 节流
		this.canvasMove = _.throttle((e) => {
			const rect = this.canvas.getBoundingClientRect();
			const clientX = e.clientX || e.touches[0].clientX;
			const clientY = e.clientY || e.touches[0].clientY;
			const posX = clientX - rect.left;
			const posY = clientY - rect.top;
			if (this.state.visible) {
				document.body.style.cursor = 'none';
				this.cursor.move(posX, posY).front();
			}
			if (this.onDraw) {
				this.tmpCircle.push(this.draw.circle(this.state.radius).move(posX, posY).fill('#fff'));
			}
		}, 10);
	}
	canvasDown(e) {
		this.onDraw = true;
		this.canvasMove(e);
	}
	canvasUp(e) {
		this.onDraw = false;
		if (this.tmpCircle.length > 0) {
			this.polyLines.push(this.tmpCircle);
			this.tmpCircle = [];
		}
		if (this.polyLines.length > 0) {
			this.setState({
				revertStatus: true
			});
		}
	}
	canvasEnter(e) {
		document.body.style.cursor = 'none';
		this.onDraw = false;
		this.setState({
			visible: true
		});
	}
	canvasLeave(e) {
		this.setState({
			visible: false
		});
		// 还原光标
		document.body.style.cursor = 'auto';
		this.cursor.move(-100, -100);
	}
	canvasRevert() {
		this.polyLines.pop().forEach((item) => {
			item.remove();
		});
		if (this.polyLines.length === 0) {
			this.setState({
				revertStatus: false
			});
		}
	}
	componentDidMount() {
		this.draw = SVG('draw');
		this.draw.rect('100%', '100%').fill('#fff');
		if (this.props.imageData) {
			this.setState({
				loading: this.state.loading + 1
			});
			// 图片最优放置
			const background = this.draw.image(this.props.imageData).loaded((info) => {
				const zoomHeight = this.canvas.clientWidth / info.width * info.height - 10;
				const zoomWidth = this.canvas.clientHeight / info.height * info.width - 10;
				if (zoomHeight > this.canvas.clientHeight) {
					background.size(zoomWidth, this.canvas.clientHeight).move((this.canvas.clientWidth - zoomWidth) / 2, 0);
				} else {
					background.size(this.canvas.clientWidth, zoomHeight).move(0, (this.canvas.clientHeight - zoomHeight) / 2);
				}
				this.setState({
					loading: this.state.loading - 1
				});
			});
		}
		// 光标初始化
		this.cursor = this.draw
			.circle(this.state.radius)
			.stroke({ width: 1, color: '#bcbcbc' })
			.fill('#fff')
			.move(-100, -100);
	}
	radiusChange(value) {
		if (!isNaN(parseInt(value))) {
			this.cursor.size(value);
			this.setState({
				radius: value
			});
		}
	}
	onSubmit() {
		this.setState({
			onSubmitLoading: this.state.onSubmitLoading + 1
		});
		const s = new XMLSerializer().serializeToString(this.draw.node);
		const encodeData = 'data:image/svg+xml;base64,' + window.btoa(s);
		this.setState({
			onSubmitLoading: this.state.onSubmitLoading - 1
		});
		this.props.onNextStep(encodeData);
	}
	render() {
		return !this.props.imageData ? (
			<h3>暂无图像数据</h3>
		) : (
			<div>
				<Row gutter={16} type="flex">
					<Col xs={24} sm={24} md={16}>
						<Spin tip="图像加载中" spinning={this.state.loading > 0}>
							<Canvas
								id="draw"
								draggable={false}
								innerRef={(canvas) => (this.canvas = canvas)}
								onMouseDown={(e) => {
									e.preventDefault();
									e.persist();
									this.canvasDown(e);
								}}
								onMouseUp={(e) => {
									e.preventDefault();
									e.persist();
									this.canvasUp(e);
								}}
								onMouseEnter={(e) => {
									this.canvasEnter(e);
								}}
								onMouseLeave={(e) => {
									this.canvasLeave(e);
								}}
								onTouchStart={(e) => {
									e.preventDefault();
									this.canvasEnter(e);
									this.canvasDown(e);
								}}
								onTouchEnd={(e) => {
									e.preventDefault();
									this.canvasLeave(e);
									this.canvasUp(e);
								}}
								onMouseMove={(e) => {
									e.preventDefault();
									e.persist();
									this.canvasMove(e);
								}}
								onTouchMove={(e) => {
									e.preventDefault();
									e.persist();
									this.canvasMove(e);
								}}
							/>
						</Spin>
					</Col>
					<Col xs={24} sm={24} md={8}>
						<div>
							<h4>橡皮大小</h4>
							<Row justify={'space-between'} align={'middle'} type="flex">
								<Slider
									min={1}
									max={50}
									value={this.state.radius}
									style={{ flexGrow: 1, marginRight: '1em' }}
									onChange={this.radiusChange.bind(this)}
								/>
								<InputNumber min={1} max={50} value={this.state.radius} onChange={this.radiusChange.bind(this)} />
							</Row>
						</div>
					</Col>
				</Row>
				<Divider />
				<Row type="flex" justify="space-between" align={'bottom'} style={{ width: '100%' }}>
					<Button onClick={this.props.onPreStep}>上一步</Button>
					<div>
						<Button onClick={this.canvasRevert.bind(this)} disabled={!this.state.revertStatus}>
							撤销
						</Button>
						<Button
							loading={this.state.onSubmitLoading > 0}
							type={'primary'}
							style={{ margin: '0 0 0 0.5em' }}
							onClick={this.onSubmit.bind(this)}
						>
							下一步
						</Button>
					</div>
				</Row>
			</div>
		);
	}
}

ImageEraser.propTypes = {
	imageData: PropTypes.string,
	onPreStep: PropTypes.func.isRequired,
	onNextStep: PropTypes.func.isRequired
};
